package com.itheima.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dto.DishDto;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.entity.Employee;
import com.itheima.entity.Category;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    //添加
    @PostMapping
    public R<String> addDish(@RequestBody DishDto dishDto){
        System.out.println(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        redisTemplate.delete("dish_"+dishDto.getCategoryId());
        return R.success("添加成功！！");
    }


    //分页查询
    @GetMapping("/page")
    public R<Page<DishDto>> selectByPage(Integer page, Integer pageSize, String name){
        log.info(page+":"+pageSize+":"+name);
        Page<Dish> page1=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> qw=new LambdaQueryWrapper<>();
        qw.like(name!=null,Dish::getName,name);
        qw.orderByDesc(Dish::getSort);
        Page<Dish> dishPage = dishService.page(page1,qw);
        Page<DishDto> dishDtoPage=new Page<>();

        //page拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        //获得records
        List<Dish> dishes=dishPage.getRecords();
        List<DishDto> list=new ArrayList<>();
        for (Dish dish:
             dishes) {
            DishDto dishDto=new DishDto();
            //dish拷贝
            BeanUtils.copyProperties(dish,dishDto);
            //获取分类名称
            long id=dish.getCategoryId();
            //查询分类名称
            Category byId = categoryService.getById(id);
            dishDto.setCategoryName(byId.getName());
            list.add(dishDto);
        }

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }


    //根据id查询方法  回显
    @GetMapping("/{id}")
    public R<DishDto> selectById(@PathVariable Long id){
        DishDto byId = dishService.getDishDto(id);
        return R.success(byId);
    }

    //更新修改内容
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateDishDto(dishDto);
        String key="dish_"+dishDto.getCategoryId();
        log.info("key="+key);
        redisTemplate.delete(key);
        return R.success("修改成功！！");
    }


    //删除菜品
    @DeleteMapping
    public R<String> delete(Long[] ids){
        log.info(ids.toString());
        //TODO 删除缓存数据
        redisTemplate.delete("dish_"+dishService.getById(ids[0]).getCategoryId());
        for (Long id:
             ids) {
            dishService.delete(id);
        }

        return R.success("删除成功！");
    }


    //修改菜品状态
    @PostMapping("/status/{status}")
    public R<String> modifyStatus(@PathVariable Integer status,Long[] ids){

        //TODO 修改菜品数据需要删除 redis
        log.info(ids.toString()+"  status::"+status);
        List<Dish> dishes=new ArrayList<>();
        for (Long id:
             ids) {
            Dish byId = dishService.getById(id);
            byId.setStatus(status);
            dishes.add(byId);
        }
        dishService.updateBatchById(dishes);
        log.info("修改后："+dishes.toString());

        //TODO 构建动态的key
        String key="dish_"+dishes.get(0).getCategoryId();
        log.info("key="+key);
        redisTemplate.delete(key);
        return R.success("修改成功！");
    }

    //套餐按分类查询菜品  需要返回口味信息
    @GetMapping("/list")
    public R<List<DishDto>> dishList(Long categoryId){

        List<DishDto> list1=null;
        //TODO 先查询redis里面有没有数据

        //动态构建key
        String key="dish_"+categoryId;
        String string1=(String) redisTemplate.opsForValue().get(key);
        list1= (List<DishDto>) JSON.parse(string1);

        //如果存在直接返回
        if (list1 != null){
            return R.success(list1);
        }

        //TODO 如果查询redis数据为空 那么需要查询数据库 然后缓存到数据库
        //查询出来的数据
        LambdaQueryWrapper<Dish> qw=new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId);
        List<Dish> list = dishService.list(qw);
        //对list进行遍历
        list1=new ArrayList<>();
        for (Dish dish:
             list) {
            //对象拷贝
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);

            //查询口味信息
            LambdaQueryWrapper<DishFlavor> qa=new LambdaQueryWrapper<>();
            qa.eq(DishFlavor::getDishId,dish.getId());
            List<DishFlavor> list2 = dishFlavorService.list(qa);

            dishDto.setFlavors(list2);

            //对象加入集合
            list1.add(dishDto);
        }

        //缓存数据   设置有效期为60分钟
        String s = JSON.toJSONString(list1);
        redisTemplate.opsForValue().set(key,s,60, TimeUnit.MINUTES);

        return R.success(list1);

    }


}
